package at.fhooe.ems.service;

import java.util.List;
import java.util.Observable;
import java.util.Observer;
import at.fhooe.ems.adapter.EnviromentData;
import at.fhooe.ems.dal.Persistence;
import at.fhooe.ems.dal.SensorDataModel;
import at.fhooe.ems.util.DataUtil;

public class AdapterDataRecipient implements Observer{
	private String jsonSensorData;
	private ServerThread serverThread;
	
	@Override
	public void update(Observable adapter, Object sensorData) {
		try{
			if(sensorData!=null){
				SensorDataModel model = mapSensorDataToModel((EnviromentData)sensorData);
				setJsonSensorData(DataUtil.convertToJSON(model));
				System.out.println("AdapterReceiver: "+jsonSensorData);
				if(serverThread!=null){
					serverThread.sendMessage(jsonSensorData,model.getActiveSensors());
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public SensorDataModel mapSensorDataToModel(EnviromentData sensorData){
		SensorDataModel model = new SensorDataModel();
		
		model.setActiveSensors(sensorData.getActiveSensors());
		model.setTemperature(sensorData.temperature);
		model.setHumidity(sensorData.humidity);
		model.setLightness(sensorData.light);
		model.setNoise(sensorData.noice);
		model.setSensorTime(sensorData.date);
		if(sensorData.smoke == 0){
			model.setSmoke(false);
		}else{
			model.setSmoke(true);
		}
		
		return model;
	}
	
	public String getJsonSensorData(){
		return jsonSensorData;
	}
	
	public void setJsonSensorData(String json){
		jsonSensorData = json;
	}
	
	public void setServerThread(ServerThread st){
		serverThread = st;
	}
}
